package com.example.c4;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;

/**
 * @author Jonathan
 * 2021/5/28 21:17
 */

@Slf4j
public class ServerSelector {

    public static void main(String[] args) throws IOException {
        Selector selector = Selector.open();

        ByteBuffer buffer = ByteBuffer.allocate(16);
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);//  设置为非阻塞模式
        log.info("register key:{}", serverSocketChannel);
        SelectionKey sscKey = serverSocketChannel.register(selector, 0, null);// 注册
        // 感兴趣的事件
        sscKey.interestOps(SelectionKey.OP_ACCEPT);

        serverSocketChannel.bind(new InetSocketAddress(8080));
        while (true) {
            // select 在事件未处理时，他不会再阻塞
            // 事件发生后 要么处理 那么取消  不能置之不理
            selector.select();// 没有事件阻塞在这个位置

            // 处理事件  内部包含了所有的事件
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                // 移除
                iterator.remove();
                log.info("key:{}", key);
//                key.cancel();
                // 建立连接
                if (key.isAcceptable()) {
                    try {
                        ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                        SocketChannel socketChannel = channel.accept();
                        log.info("建立连接socketChannel:{}", socketChannel);
                        socketChannel.configureBlocking(false);
                        ByteBuffer allocate = ByteBuffer.allocate(16);
                        SelectionKey scKey = socketChannel.register(selector, 0, allocate);
                        scKey.interestOps(SelectionKey.OP_READ); // 关注读事件
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else if (key.isReadable()) {
                    try {
                        SocketChannel channel = (SocketChannel) key.channel();
                        ByteBuffer buffer1 = (ByteBuffer) key.attachment();
                        int read = channel.read(buffer1);// 正常断开返回值是-1
                        if (read == -1) {
                            key.cancel();
                        } else {
                            split(buffer1);
                            if (buffer1.position() == buffer1.limit()) {
                                ByteBuffer newByteBuffer = ByteBuffer.allocate(buffer1.capacity() * 2);
                                newByteBuffer.flip();
                                newByteBuffer.put(buffer1);
                                // 将新的放上去
                                key.attach(newByteBuffer);
                            }
                            Buffer flip = buffer1.flip();
                            buffer1.clear();
                            log.info("{}", Charset.defaultCharset().decode(buffer1));
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        key.cancel(); // 取消  从selector的key中删除
                    }
                }
            }

        }


    }

    private static void split(ByteBuffer allocate) {

    }
}
